﻿using bianzhuo.SupportPlatform.BLL;
using bianzhuo.SupportPlatform.COL;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.Data;

namespace bianzhuo.SupportPlatform.WebUI.BzBusiness
{
    public partial class WxFansDefaults1 : System.Web.UI.Page
    {
        string mainWhere = " AttentionState=1 ";
        protected string MicroId = "";
        protected int PromotFansCount = 0;

        protected void Page_Load(object sender, EventArgs e)
        {
            bianzhuo.SupportPlatform.WebUI.BzBusiness.BusinessBase.LoginStatusChechk();
            WebUI.BzBusiness.BusinessBase.CheckRules();
            setWhere();
            getRequestValues();
        }

        private void setWhere()
        {
            if (Request.QueryString["groupID"] != null)
            {
                mainWhere += " and UserGroup=" + Request.QueryString["groupID"].ToString();
            }
            if (Request["stext"] != null)
            {
                mainWhere += " and (NickName like '%" + Request["stext"].ToString() + "%' "
                    + " or RealName like '%" + Request["stext"].ToString() + "%' "
                + " or MemoName like '%" + Request["stext"].ToString() + "%' )";
            }
            if (Request["source"] != null)
            {
                mainWhere += " and Source=" + Convert.ToInt32(Request["source"]);

            }
        }
        private void getRequestValues()
        {
            HttpCookie bzBusiness = Request.Cookies["BzSupport_Business"];
            string BusAdminID = bzBusiness.Values["BusinessAdminID"].ToString();
            string BusinessID = bzBusiness.Values["BusinessID"].ToString();
            string wxID = bzBusiness.Values["wxID"].ToString();
            MicroId = wxID;
            // string sql = "select count(*) from BusinessUserInfo where MicroId="+wxID + " and Source=30";
            //PromotFansCount = Convert.ToInt32(SFL.SqlHelper.GetSingle(sql));

            mainWhere += " and MicroId='" + wxID + "' and UserCardStatus!=2 and AttentionState=1";
            int GetCount = 0;
            List<BusinessUserInfo> listFans = BusinessUserInfoBLL.GetList(AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex, mainWhere, out GetCount);
            AspNetPager1.RecordCount = GetCount;
            listFansRepeater.DataSource = listFans;
            listFansRepeater.DataBind();
        }
        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            if (AspNetPager1.CurrentPageIndex > 0)
            {
                getRequestValues();
            }
        }

        public static string GetDataByBusinessIDAndMicroIdAndGroupName(string groupName)
        {
            try
            {
                HttpCookie bzBusiness = HttpContext.Current.Request.Cookies["BzSupport_Business"];
                string BusAdminID = bzBusiness.Values["BusinessAdminID"].ToString();
                string BusinessID = bzBusiness.Values["BusinessID"].ToString();
                string wxID = bzBusiness.Values["wxID"].ToString();
                UserGroup u = BLL.UserGroupBLL.GetDataByBusinessIDAndMicroIdAndGroupName(int.Parse(BusinessID), int.Parse(wxID), groupName);
                return u.GroupId.ToString();
            }
            catch
            {
                return string.Empty;
            }
        }
        public bool DateDiff(DateTime LastDate)
        {
            TimeSpan ts1 = new TimeSpan(LastDate.Ticks);
            TimeSpan ts2 = new TimeSpan(DateTime.Now.Ticks);
            TimeSpan ts = ts1.Subtract(ts2).Duration();
            if (ts.Days > 0)
            {
                return true;
            }
            else if (ts.Hours > 1)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 获取粉丝列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_list_Click(object sender, EventArgs e)
        {

            HttpCookie bzBusiness = Request.Cookies["BzSupport_Business"];
            string BusAdminID = bzBusiness.Values["BusinessAdminID"].ToString();
            string BusinessID = bzBusiness.Values["BusinessID"].ToString();
            string WxID = bzBusiness.Values["WxID"].ToString();
            // MerchantWx WxInfo = MerchantWxBLL.GetDataByMicroId(WxID);
            // WxInfo.KeyAppCode = SFL.WxAPIx.GetKeyCode((int)WxInfo.MicroId);
            //清空所有关注
            string sql = "update businessuserinfo set AttentionState=0  where microid = " + WxID + " and AttentionState = 1";
            SFL.SqlHelper.GetSingle(sql);

            GetWxUserOpenList("https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + SFL.WxAPIx.GetKeyCode(int.Parse(WxID)), WxID);
            string ss = "";
            if (Request.QueryString["groupID"] != null)
            {
                ss += "&UserGroup=" + Request.QueryString["groupID"].ToString();
            }
            if (Request.QueryString["stext"] != null)
            {
                ss += "&stext=" + Request.QueryString["stext"].ToString();
            }
            Response.Redirect("page_cg.html?returnUrl=WxFansDefaults.aspx?MicroId=" + WxID + "" + ss + "");

        }

        /// <summary>
        /// 更新会员信息
        /// </summary>
        /// <param name="OpenID"></param>
        /// <param name="WxID"></param>
        /// <param name="BusinessID"></param>
        public void UpdateWxUserInfo(string OpenID, string WxID, string BusinessID)
        {
            try
            {
                BLL.BusinessUserInfoBLL1.UpdateUserInfoFromWeixin(OpenID, Convert.ToInt32(WxID));

            }
            catch
            {

            }

        }

        /// <summary>
        /// 获取微信粉丝OpenID列表，同步到本地数据库
        /// </summary>
        /// <param name="GetOpenIDListUrl"></param>
        /// <param name="WxID"></param>
        public void GetWxUserOpenList(string GetOpenIDListUrl, string WxID)
        {
            System.Net.HttpWebRequest hwr = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(GetOpenIDListUrl);
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;
            hwr.Timeout = 19600;
            System.Net.HttpWebResponse hwrs = (System.Net.HttpWebResponse)hwr.GetResponse();
            System.IO.Stream myStream = hwrs.GetResponseStream();

            System.IO.StreamReader sr = new System.IO.StreamReader(myStream, System.Text.Encoding.UTF8);
            string textResponse = sr.ReadToEnd();
            JsonReader ser = new JsonReader(new System.IO.StringReader(textResponse));
            JsonSerializer serializer = new JsonSerializer();
            WxUserInfoList foo = (WxUserInfoList)serializer.Deserialize(ser, typeof(WxUserInfoList));
            string totalCount = foo.count.ToString();
            if (totalCount.Length > 0 && int.Parse(totalCount) > 0)
            {

                string sql = "select distinct openid from businessuserinfo where openid is not null and microid = " + WxID + "";
                DataTable dt = SFL.SqlHelper.ExecuteDataSet(sql).Tables[0];

                dt.PrimaryKey = new DataColumn[] { dt.Columns[0] };

                //int count = 0;

                List<string> listOpenID = foo.data["openid"];
                string openidstr = "";

                MerchantWx newWx = MerchantWxBLL.GetDataByMicroId(int.Parse(WxID));
                Action<string, int> UpdateUserInfoFromWeixin = (obj, s) => BLL.BusinessUserInfoBLL1.UpdateUserInfoFromWeixin(obj, s);
                Action<string, string, string> initFans = (s1, s2, s3) => BLL.BusinessUserInfoBLL.InitFans(s1, s2, s3);
                for (int i = 0; i < listOpenID.Count; i++)
                {
                    if (dt.Rows.Contains(listOpenID[i]))
                    {
                        openidstr += "'" + listOpenID[i] + "',";
                    }
                    else
                    {
                        initFans(newWx.MerchantId.MerchantId.ToString(), WxID, listOpenID[i]);
                    }

                    BLL.BusinessUserInfoBLL1.UpdateUserInfoFromWeixin(listOpenID[i], int.Parse(WxID));

                }
                if (openidstr.IndexOf(",") > -1)
                {
                    openidstr = openidstr.Substring(0, openidstr.Length - 1);
                }
                sql = "update businessuserinfo set AttentionState=1  where microid = " + WxID + " and openid in (" + openidstr + ")";
                SFL.SqlHelper.GetSingle(sql);
            }
            else
            {

                Page.ClientScript.RegisterStartupScript(GetType(), "err", "alert('" + foo.errcode + ":" + foo.errmsg + "');");
            }
            if (int.Parse(totalCount) > 0)
            {

                GetWxUserOpenList("https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + SFL.WxAPIx.GetKeyCode(int.Parse(WxID)) + "&next_openid=" + foo.next_openid, WxID);
            }

        }

        /// <summary>
        /// 检测openID是否在库入库
        /// </summary>
        /// <param name="openID"></param>
        /// <param name="newWx"></param>
        protected void UpdateOpenIDStatus(string openID, MerchantWx newWx)
        {
            BusinessUserInfo isHave = BusinessUserInfoBLL.GetDataByOpenID(openID);
            string WxID = newWx.MicroId.ToString();
            if (isHave == null)
            {
                BLL.BusinessUserInfoBLL1.InitFans(newWx.MerchantId.MerchantId.ToString(), WxID, openID);
                //UpdateWxUserInfo(openID, WxID, isHave.MerchantId.ToString());       
            }
            else if (isHave != null)
            {
                isHave.AttentionState = 1;
                BusinessUserInfoBLL.Update(isHave);
                //UpdateWxUserInfo(openID, WxID, isHave.MerchantId.ToString());
            }
        }



        /// <summary>
        /// 更新粉丝状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_fans_Click(object sender, EventArgs e)
        {
            HttpCookie bzBusiness = Request.Cookies["BzSupport_Business"];
            string BusAdminID = bzBusiness.Values["BusinessAdminID"].ToString();
            string BusinessID = bzBusiness.Values["BusinessID"].ToString();
            string MicroId = bzBusiness.Values["WxID"].ToString();
            string mainWhere = "MerchantId=" + BusinessID;
            mainWhere += " and MicroId=" + MicroId;
            Button btn = sender as Button;
            if (!string.IsNullOrWhiteSpace(Request.Params["cks"]))
            {
                mainWhere += " and UserId in (" + Request.Params["cks"] + ") ";
            }
            if (btn.ID == "btn_updatespaceheadpic")
            {
                mainWhere += " and UserPictrue is null and AttentionState=1 ";
            }
            int getCount = 0;
            List<BusinessUserInfo> mylist = BusinessUserInfoBLL.GetList(100000000, 1, mainWhere, out getCount);
            List<string> openidarr = new List<string>();
            mylist.ForEach(delegate (BusinessUserInfo user)
            {
                openidarr.Add(user.OpenID);
            });
            Action<Dictionary<string, object>, string> UpdateUserInfoFromWeixin = (obj, s) => BLL.BusinessUserInfoBLL1.UpdateUserInfoFromWeixin(obj, s);
            int stepmax = mylist.Count > 100 ? 100 : mylist.Count;
            for (int i = 0; i < mylist.Count; i += stepmax)
            {
                string[] openids = openidarr.GetRange(i, (i + stepmax > openidarr.Count) ? (openidarr.Count - i) : stepmax).ToArray();
                string respon = SFL.WxAPIx.GetUserInfoListByOpenIDs(int.Parse(MicroId), openids);
                Dictionary<string, object> dict = SFL.StringHelper.Json2Dictionary(respon);
                if (dict != null && dict.ContainsKey("user_info_list"))
                {
                    Newtonsoft.Json.JavaScriptArray arr = dict["user_info_list"] as Newtonsoft.Json.JavaScriptArray;
                    foreach (Dictionary<string, object> obj in arr)
                    {
                        if (obj.ContainsKey("openid"))
                        {
                            UpdateUserInfoFromWeixin(obj, MicroId);
                        }
                    }

                }
            }
            string ss = "";
            if (Request.QueryString["groupID"] != null)
            {
                ss += "&UserGroup=" + Request.QueryString["groupID"].ToString();
            }
            if (Request.QueryString["stext"] != null)
            {
                ss += "&stext=" + Request.QueryString["stext"].ToString();
            }
            Response.Redirect("page_cg.html?returnUrl=WxFansDefaults.aspx?MicroId=" + bzBusiness.Values["wxID"].ToString() + "" + ss + "");
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            HttpCookie bzBusiness = Request.Cookies["BzSupport_Business"];
            string BusAdminID = bzBusiness.Values["BusinessAdminID"].ToString();
            string BusinessID = bzBusiness.Values["BusinessID"].ToString();
            string MicroId = Request["MicroId"].ToString();
            string mainWhere = "MerchantId=" + BusinessID;
            Button b = (Button)sender;
            UpdateWxUserInfo(b.CommandArgument, MicroId, BusinessID);
            string ss = "";
            if (Request.QueryString["groupID"] != null)
            {
                ss += "&UserGroup=" + Request.QueryString["groupID"].ToString();
            }
            if (Request.QueryString["stext"] != null)
            {
                ss += "&stext=" + Request.QueryString["stext"].ToString();
            }
            Response.Redirect("page_cg.html?returnUrl=WxFansDefaults.aspx?MicroId=" + bzBusiness.Values["wxID"].ToString() + "" + ss + "");
        }

        protected void ButtonSendMessageCommand_Click(object sender, EventArgs e)
        {

            if (txtSendContent.Value == "")
            {
                Page.ClientScript.RegisterStartupScript(GetType(), "save", "<script>alert('请先输入回复内容。');location.reload();</script>");
                return;
            }
            HttpCookie bzBusiness = Request.Cookies["BzSupport_Business"];
            string BusAdminID = bzBusiness.Values["BusinessAdminID"].ToString();
            string BusinessID = bzBusiness.Values["BusinessID"].ToString();
            string MicroId = Request["MicroId"].ToString();

            MessageInfo BusSendMessage = new MessageInfo();
            BusSendMessage.MessageModel = 2;
            BusSendMessage.MessageReceiver = int.Parse(toUserId.Value);
            BusSendMessage.MessageSender = int.Parse(MicroId);
            BusSendMessage.MessageType = 1;
            BusSendMessage.ReceiveStatus = 0;
            BusSendMessage.SendContent = txtSendContent.Value;
            BusSendMessage.SendTime = DateTime.Now;

            MessageInfoBLL.Insert(BusSendMessage);

            BusinessUserInfo UserInfo = BusinessUserInfoBLL.GetDataByUserId(int.Parse(toUserId.Value));
            MessageInfoBLL.UpdateState(MicroId, toUserId.Value);
            MerchantWx BusinessWx = MerchantWxBLL.GetDataByMicroId(MicroId);
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;

            string HttpUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + SFL.WxAPIx.GetKeyCode(int.Parse(MicroId));
            string JsonString = "{"
                                + "\"touser\":\"" + UserInfo.OpenID + "\","
                                + "\"msgtype\":\"text\","
                                + "\"text\":{"
                                         + "\"content\":\"" + txtSendContent.Value + "\""
                                + "}"
                            + "}\";";
            byte[] send = System.Text.Encoding.UTF8.GetBytes(JsonString);
            System.Net.HttpWebRequest MyWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(HttpUrl);

            MyWebRequest.ContentType = "application/x-www-form-urlencoded";
            MyWebRequest.ContentLength = send.Length;
            MyWebRequest.AllowAutoRedirect = true;
            MyWebRequest.Method = "POST";
            System.IO.Stream newStream = MyWebRequest.GetRequestStream();
            newStream.Write(send, 0, send.Length);
            newStream.Flush();
            newStream.Close();
            System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)MyWebRequest.GetResponse();//获取响应
            System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
            string textResponse = sr.ReadToEnd();

            string msg = "";
            if (textResponse.IndexOf("ok") >= 0) msg = "发送成功";
            else if (textResponse.IndexOf("45015") >= 0) msg = "回复时间超过24小时限制";
            else msg = "发送失败";

            Page.ClientScript.RegisterStartupScript(GetType(), "save", "<script>alert('" + msg + "。');location.reload();</script>");

        }
        /// <summary>
        /// 根据user的CardLeveL返回会员等级名称
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public string getMemberClass(object obj)
        {
            try
            {
                int id = Convert.ToInt32(obj);
                COL.BusinessCardLevelInfo cl = BLL.BusinessCardLevelInfoBLL.GetDataByCardLeveLID(id);
                return cl.LevelName;
            }
            catch
            {
                return "";
            }
        }

        //从微信同步会员组
        protected void btn_UpdateGroupFromWeiXin_Click(object sender, EventArgs e)
        {

            HttpCookie bzBusiness = Request.Cookies["BzSupport_Business"];
            string BusAdminID = bzBusiness.Values["BusinessAdminID"].ToString();
            string BusinessID = bzBusiness.Values["BusinessID"].ToString();
            string WxID = bzBusiness.Values["WxID"].ToString();
            if (SFL.WxAPIx.UpdateGroupFromWeiXin(int.Parse(WxID)))
            {
                Page.ClientScript.RegisterStartupScript(GetType(), "sync", "<script>alert('从微信同步会员组成功');</script>");
            }
            else
            {
                Page.ClientScript.RegisterStartupScript(GetType(), "sync", "<script>alert('从微信同步会员组失败');</script>");
            }


        }
        //同步会员组至微信
        protected void btn_UpdateGroupFromWZZ_Click(object sender, EventArgs e)
        {

            HttpCookie bzBusiness = Request.Cookies["BzSupport_Business"];
            string BusAdminID = bzBusiness.Values["BusinessAdminID"].ToString();
            string BusinessID = bzBusiness.Values["BusinessID"].ToString();
            string WxID = bzBusiness.Values["WxID"].ToString();
            if (SFL.WxAPIx.UpdateGroupFromWZZ(int.Parse(WxID)))
            {
                Page.ClientScript.RegisterStartupScript(GetType(), "sync", "<script>alert('同步会员组至微信成功');</script>");
            }
            else
            {
                Page.ClientScript.RegisterStartupScript(GetType(), "sync", "<script>alert('同步会员组至微信失败');</script>");
            }


        }

    }
}